/**
 * 953. 验证外星语词典
 * https://leetcode.cn/problems/verifying-an-alien-dictionary/
 */

const codeA = 'a'.charCodeAt(0);

/**
 * @param {string[]} words
 * @param {string} order
 * @return {boolean}
 */
function isAlienSorted(words, order) {
  const map = new Array(26);
  for (let i = 0; i < order.length; i += 1) {
    map[order.charCodeAt(i) - codeA] = i;
  }
  for (let i = 1; i < words.length; i += 1) {
    const cur = words[i];
    const pre = words[i - 1];
    const minLength = Math.min(cur.length, pre.length);
    let flag = false;
    for (let j = 0; j < minLength; j += 1) {
      const preIndex = map[pre.charCodeAt(j) - codeA];
      const curIndex = map[cur.charCodeAt(j) - codeA];
      if (preIndex > curIndex) {
        return false;
      }
      if (preIndex < curIndex) {
        flag = true;
        break;
      }
    }
    if (!flag && pre.length > cur.length) {
      return false;
    }
  }
  return true;
}

console.log(isAlienSorted(['hello', 'leetcode'], 'hlabcdefgijkmnopqrstuvwxyz') === true);
console.log(isAlienSorted(['word', 'world', 'row'], 'worldabcefghijkmnpqstuvxyz') === false);
console.log(isAlienSorted(['apple', 'app'], 'abcdefghijklmnopqrstuvwxyz') === false);
